package net.zio.kamenriderzioaddon.ridersystem.behavior.impl;

import net.minecraft.ChatFormatting;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.effect.MobEffectInstance;
import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.zio.kamenriderzioaddon.entity.GeizmajestyspecialeffectsEntity;
import net.zio.kamenriderzioaddon.enums.HenshinState;
import net.zio.kamenriderzioaddon.enums.SoundType;
import net.zio.kamenriderzioaddon.init.KamenRiderZioAddonModEntities;
import net.zio.kamenriderzioaddon.init.KamenRiderZioAddonModGeckoLibArmors;
import net.zio.kamenriderzioaddon.init.KamenRiderZioAddonModItems;
import net.zio.kamenriderzioaddon.init.KamenRiderZioAddonModSounds;
import net.zio.kamenriderzioaddon.network.NetworkHandler;
import net.zio.kamenriderzioaddon.network.message.AnimationMessage;
import net.zio.kamenriderzioaddon.ridersystem.behavior.IAwakeningHenshinBehavior;
import net.zio.kamenriderzioaddon.ridersystem.data.PlayerDataManager;
import net.zio.kamenriderzioaddon.ridersystem.registry.AwakeningConfig;
import net.zio.kamenriderzioaddon.ridersystem.registry.FullRiderConfig;
import net.zio.kamenriderzioaddon.ridersystem.util.DelayedTask;
import net.zio.kamenriderzioaddon.ridersystem.util.HenshinUtils;
import net.zio.kamenriderzioaddon.ridersystem.util.SpecialEffectsUtils;

public class GeizMajestyBehavior implements IAwakeningHenshinBehavior {


    /**
     * 处理 standby 形态
     * @param player 玩家实例
     * @param fullRiderConfig 完整骑士配置
     * @param awakeningConfig 强化形态配置
     */
    @Override
    public void handleStandbyAwakening(Player player, FullRiderConfig fullRiderConfig, AwakeningConfig awakeningConfig) {
        // 检查是否佩戴对应腰带和持有对应变身道具
        if (player.getItemBySlot(EquipmentSlot.LEGS).getItem() ==
                KamenRiderZioAddonModGeckoLibArmors.GeckoLibArmorItems.ZIKUDRIVER_LEGGINGS.get()) {
            if (player.getItemBySlot(EquipmentSlot.MAINHAND).getItem() == KamenRiderZioAddonModItems.GEIZWATCH.get() &&
                    player.getItemBySlot(EquipmentSlot.OFFHAND).getItem() == KamenRiderZioAddonModItems.GEIZ_MAJESTY_WATCH.get()) {
                // 调用主副手插入表盘流程
                handleWatchInsert(player, fullRiderConfig, awakeningConfig);
            }
        } else if (player.getItemBySlot(EquipmentSlot.LEGS).getItem() ==
                KamenRiderZioAddonModGeckoLibArmors.GeckoLibArmorItems.ZIKUDRIVERWITHGEIZWATCH_LEGGINGS.get()) {
            if (player.getItemBySlot(EquipmentSlot.OFFHAND).getItem() == KamenRiderZioAddonModItems.GEIZ_MAJESTY_WATCH.get()) {
                // 调用副手插入表盘流程
                offhandWatchInsert(player, fullRiderConfig, awakeningConfig);
            }
        }
    }

    /**
     * 处理快速变身逻辑
     *
     * @param player 进行快速变身的玩家对象
     * @param fullRiderConfig 完整骑士配置
     * @param awakeningConfig 强化形态配置
     */
    @Override
    public void handleQuickTransformation(Player player, FullRiderConfig fullRiderConfig, AwakeningConfig awakeningConfig) {
        // 检查是否佩戴对应腰带和持有对应变身道具
        if (player.getItemBySlot(EquipmentSlot.LEGS).getItem() ==
                KamenRiderZioAddonModGeckoLibArmors.GeckoLibArmorItems.ZIKUDRIVER_LEGGINGS.get()) {
            if (player.getItemBySlot(EquipmentSlot.MAINHAND).getItem() == KamenRiderZioAddonModItems.GEIZWATCH.get() &&
                    player.getItemBySlot(EquipmentSlot.OFFHAND).getItem() == KamenRiderZioAddonModItems.GEIZ_MAJESTY_WATCH.get()) {
                // 调用主副手插入表盘快速变身流程
                handleWatchQuickInsert(player, fullRiderConfig, awakeningConfig);
            }
        } else if (player.getItemBySlot(EquipmentSlot.LEGS).getItem() ==
                KamenRiderZioAddonModGeckoLibArmors.GeckoLibArmorItems.ZIKUDRIVERWITHGEIZWATCH_LEGGINGS.get()) {
            if (player.getItemBySlot(EquipmentSlot.OFFHAND).getItem() == KamenRiderZioAddonModItems.GEIZ_MAJESTY_WATCH.get()) {
                // 调用副手插入表盘快速变身流程
                offhandWatchQuickInsert(player, fullRiderConfig, awakeningConfig);
            }
        }
    }

    /**
     * 主副手插入表盘快速变身流程
     *
     * @param player 进行快速变身的玩家对象
     * @param fullRiderConfig 完整骑士配置
     * @param awakeningConfig 强化形态配置
     */
    private void handleWatchQuickInsert(Player player, FullRiderConfig fullRiderConfig, AwakeningConfig awakeningConfig) {
        // 保存玩家当前装备（全部）
        CompoundTag standbyGear = HenshinUtils.getStandbyGear(player);
        CompoundTag activeGear = HenshinUtils.getActiveGear(player);

        // 保存完整装甲套装
        standbyGear.put("mainhand", player.getItemBySlot(EquipmentSlot.MAINHAND).save(new CompoundTag()));
        standbyGear.put("offhand", player.getItemBySlot(EquipmentSlot.OFFHAND).save(new CompoundTag()));
        activeGear.put("head", player.getItemBySlot(EquipmentSlot.HEAD).save(new CompoundTag()));
        activeGear.put("chest", player.getItemBySlot(EquipmentSlot.CHEST).save(new CompoundTag()));
        standbyGear.put("legs", player.getItemBySlot(EquipmentSlot.LEGS).save(new CompoundTag()));
        activeGear.put("feet", player.getItemBySlot(EquipmentSlot.FEET).save(new CompoundTag()));


        // 移除主副手道具
        HenshinUtils.removeMainhandItem(player,awakeningConfig.getMainHenshinItem());
        HenshinUtils.removeMainhandItem(player,awakeningConfig.getOffhandHenshinItem());

        //装备强化形态套装
        awakeningConfig.equipFullArmorSet(player);

        // 播放变身音效
        SoundEvent transformSound = awakeningConfig.getAwakeningSounds().get(SoundType.TRANSFORM);
        if (transformSound != null) {
            HenshinUtils.playSound(player, transformSound);
        }

        // 更新玩家状态
        PlayerDataManager data = PlayerDataManager.get(player);
        data.setStandbyGear(standbyGear);
        data.setActiveGear(activeGear);
        data.setActiveRiderName(fullRiderConfig.getRiderName());
        data.setActiveAwakeningName(awakeningConfig.getName());
        data.setCurrentState(HenshinState.ACTIVE_AWAKENING);


        // 保存数据
        data.saveToPlayer(player);
        data.sync(player);
    }

    /**
     * 副手插入表盘快速变身流程
     *
     * @param player 进行快速变身的玩家对象
     * @param fullRiderConfig 完整骑士配置
     * @param awakeningConfig 强化形态配置
     */
    private void offhandWatchQuickInsert(Player player, FullRiderConfig fullRiderConfig, AwakeningConfig awakeningConfig) {
        // 保存玩家当前装备（全部）
        CompoundTag standbyGear = HenshinUtils.getStandbyGear(player);

        // 保存副手变身道具
        standbyGear.put("offhand", player.getItemBySlot(EquipmentSlot.OFFHAND).save(new CompoundTag()));

        // 移除主副手道具
        HenshinUtils.removeMainhandItem(player,awakeningConfig.getOffhandHenshinItem());

        //装备强化形态套装
        awakeningConfig.equipFullArmorSet(player);

        // 播放变身音效
        SoundEvent transformSound = awakeningConfig.getAwakeningSounds().get(SoundType.TRANSFORM);
        if (transformSound != null) {
            HenshinUtils.playSound(player, transformSound);
        }

        // 更新玩家状态
        PlayerDataManager data = PlayerDataManager.get(player);
        data.setStandbyGear(standbyGear);
        data.setActiveRiderName(fullRiderConfig.getRiderName());
        data.setActiveAwakeningName(awakeningConfig.getName());
        data.setCurrentState(HenshinState.ACTIVE_AWAKENING);


        // 保存数据
        data.saveToPlayer(player);
        data.sync(player);
    }




    // 主副手插入表盘待机
    private void handleWatchInsert(Player player, FullRiderConfig fullRiderConfig, AwakeningConfig awakeningConfig) {
        String animationName1 = "mainhand_insert_watch";
        String animationName2 = "offhand_insert_watch";
        if (player instanceof ServerPlayer sp) {
            NetworkHandler.sendToTrackingPlayers(
                    new AnimationMessage(animationName1, player.getUUID(), true),
                    sp
            );

        }
        // 获取 PlayerDataManager 实例
        PlayerDataManager dataManager = PlayerDataManager.get(player);
        // 保存腿甲（腰带）和主手物品
        CompoundTag standbyGear = new CompoundTag();


        // 1. 标记变身中
        dataManager.setHenshining(true);
        dataManager.sync(player);

        //播放主手插入表盘动画
        HenshinUtils.sendAnimationMessage(player, animationName1);
        //播放表盘插入音效
        player.level.playSound(null, player.blockPosition(), KamenRiderZioAddonModSounds.REGISTRY.get(new ResourceLocation("kamen_rider_zio_addon:insert_watch")), SoundSource.PLAYERS, 5F, 1F);
        // 延迟刻：播放音效（15 ticks 后）,向客户端广播动画
        DelayedTask.run(player.level, 15, () -> {
            standbyGear.put("legs", player.getItemBySlot(EquipmentSlot.LEGS).save(new CompoundTag()));
            standbyGear.put("mainhand", player.getItemBySlot(EquipmentSlot.MAINHAND).save(new CompoundTag()));
            awakeningConfig.setStandbyGear(player, standbyGear);
            if (player instanceof ServerPlayer sp) {
                NetworkHandler.sendToTrackingPlayers(
                        new AnimationMessage(animationName2, player.getUUID(), true),
                        sp
                );
            }
            //移除主手变身道具
            HenshinUtils.removeMainhandItem(player,awakeningConfig.getMainHenshinItem());
            // 装备腰带
            fullRiderConfig.equipBelt(player);
            // 保存数据
            dataManager.saveToPlayer(player);
            dataManager.sync(player);
            //播放副手插入表盘动画
            HenshinUtils.sendAnimationMessage(player, animationName2);
            //播放表盘插入音效
            player.level.playSound(null, player.blockPosition(), KamenRiderZioAddonModSounds.REGISTRY.get(new ResourceLocation("kamen_rider_zio_addon:insert_watch")), SoundSource.PLAYERS, 5F, 1F);
        });

        // 延迟刻：播放音效（20 ticks 后）
        DelayedTask.run(player.level, 20, () -> {
            SoundEvent sound = fullRiderConfig.getSoundMap().get(SoundType.STANDBY);
            if (sound != null) {
                player.level.playSound(null, player.blockPosition(), sound, SoundSource.PLAYERS, 5F, 1F);
            }
        });
        // 延迟刻：播放音效（30 ticks 后）
        DelayedTask.run(player.level, 30, () -> {

            standbyGear.put("offhand", player.getItemBySlot(EquipmentSlot.OFFHAND).save(new CompoundTag()));
            awakeningConfig.setStandbyGear(player, standbyGear);
            //移除副手道具
            HenshinUtils.removeOffhandItem(player,awakeningConfig.getOffhandHenshinItem());
            // 装备腰带
            awakeningConfig.equipBelt(player);
            // 设置状态和消息
            fullRiderConfig.setCurrentState(player, HenshinState.STANDBY_AWAKENING);
            fullRiderConfig.sendMessage(player, "§6 " + fullRiderConfig.getRiderName(), ChatFormatting.YELLOW);

            // 保存数据
            dataManager.setHenshining(false);
            dataManager.saveToPlayer(player);
            dataManager.sync(player);
        });
        // 延迟刻：播放音效（40 ticks 后）
        DelayedTask.run(player.level, 35, () -> {
            SoundEvent sound = awakeningConfig.getAwakeningSounds().get(SoundType.STANDBY);
            if (sound != null) {
                player.level.playSound(null, player.blockPosition(), sound, SoundSource.PLAYERS, 5F, 1F);
            }

        });
    }


    // 副手插入表盘待机
    private void offhandWatchInsert(Player player, FullRiderConfig fullRiderConfig, AwakeningConfig awakeningConfig) {
        String animationName = "offhand_insert_watch";
        if (player instanceof ServerPlayer sp) {
            NetworkHandler.sendToTrackingPlayers(
                    new AnimationMessage(animationName, player.getUUID(), true),
                    sp
            );
        }
        // 获取 PlayerDataManager 实例
        PlayerDataManager dataManager = PlayerDataManager.get(player);
        // 获取玩家管理器中的待机物品
        CompoundTag standbyGear = dataManager.getStandbyGear();


        // 1. 标记变身中
        dataManager.setHenshining(true);
        dataManager.sync(player);

        //播放副手插入表盘动画
        HenshinUtils.sendAnimationMessage(player, animationName);
        //播放表盘插入音效
        player.level.playSound(null, player.blockPosition(), KamenRiderZioAddonModSounds.REGISTRY.get(new ResourceLocation("kamen_rider_zio_addon:insert_watch")), SoundSource.PLAYERS, 5F, 1F);

        // 延迟刻：播放音效（15 ticks 后）
        DelayedTask.run(player.level, 15, () -> {

            standbyGear.put("offhand", player.getItemBySlot(EquipmentSlot.OFFHAND).save(new CompoundTag()));
            System.out.println("存储时待机物品"+dataManager.getStandbyGear());
            awakeningConfig.setStandbyGear(player, standbyGear);
            //移除副手道具
            HenshinUtils.removeOffhandItem(player,awakeningConfig.getOffhandHenshinItem());
            // 装备腰带
            awakeningConfig.equipBelt(player);
            // 设置状态和消息
            fullRiderConfig.setCurrentState(player, HenshinState.STANDBY_AWAKENING);
            fullRiderConfig.sendMessage(player, "§6 " + fullRiderConfig.getRiderName(), ChatFormatting.YELLOW);

            // 保存数据
            dataManager.setHenshining(false);
            dataManager.saveToPlayer(player);
            dataManager.sync(player);
        });
        // 延迟刻：播放音效（20 ticks 后）
        DelayedTask.run(player.level, 20, () -> {
            SoundEvent sound = awakeningConfig.getAwakeningSounds().get(SoundType.STANDBY);
            if (sound != null) {
                player.level.playSound(null, player.blockPosition(), sound, SoundSource.PLAYERS, 5F, 1F);
            }
        });
    }

    /**
     * 处理强化形态变身
     * @param player 玩家实例
     * @param fullRiderConfig 基础骑士配置
     * @param awakeningConfig 强化形态配置
     */
    @Override
    public void handleAwakeningHenshin(Player player, FullRiderConfig fullRiderConfig, AwakeningConfig awakeningConfig) {
        // 动画消息
        String animationName = "geiz_majesty_complete";
        if (player instanceof ServerPlayer sp) {
            NetworkHandler.sendToTrackingPlayers(
                    new AnimationMessage(animationName, player.getUUID(), true),
                    sp
            );
        }

        // 获取PlayerDataManager
        PlayerDataManager dataManager = PlayerDataManager.get(player);

        // 1. 标记变身中
        dataManager.setHenshining(true);
        dataManager.sync(player);

        // 2. 向客户端广播动画
        HenshinUtils.sendAnimationMessage(player, animationName);
        spawnSpecialEffects(player);

        // 3. 保存当前基础驱动器
        ItemStack originalLeggings = player.getItemBySlot(EquipmentSlot.LEGS).copy();

        // 4. 在110ticks后，将腿部护甲替换为旋转驱动器
        DelayedTask.run(player.level, 110, () -> {
            // 设置旋转驱动器
            ItemStack zhuanLeggings = new ItemStack(KamenRiderZioAddonModGeckoLibArmors.GeckoLibArmorItems.ZIKUDRIVERWITHGEIZMAJESTYWATCHZHUAN_LEGGINGS.get());
            player.setItemSlot(EquipmentSlot.LEGS, zhuanLeggings);
        });

        // 5. 在120ticks后，恢复为普通驱动器,并播放音效
        DelayedTask.run(player.level, 120, () -> {
            fullRiderConfig.sendMessage(player, "§6MAJESTY TIME", ChatFormatting.GREEN);
            // 恢复普通驱动器
            player.setItemSlot(EquipmentSlot.LEGS, originalLeggings);
            // 停止待机音效
            HenshinUtils.stopSound(player, fullRiderConfig.getSoundMap().get(SoundType.STANDBY));
            HenshinUtils.stopSound(player, awakeningConfig.getAwakeningSounds().get(SoundType.STANDBY));

            // 播放变身音效
            SoundEvent sound = awakeningConfig.getAwakeningSounds().get(SoundType.TRANSFORM);
            if (sound != null) {
                player.level.playSound(null, player.blockPosition(), sound, SoundSource.PLAYERS, 5F, 1F);
            }
        });

        // 7. 存储当并清除当前装备
        DelayedTask.run(player.level, 205, () -> {
            // 保存头盔、胸甲、靴子
            CompoundTag activeGear = dataManager.getActiveGear();
            //判断当前是否穿着基础形态的套装
            if (!HenshinUtils.isEquippedArmor(player,fullRiderConfig.getFullArmorSet())) {
                activeGear.put("head", player.getItemBySlot(EquipmentSlot.HEAD).save(new CompoundTag()));
                activeGear.put("chest", player.getItemBySlot(EquipmentSlot.CHEST).save(new CompoundTag()));
                activeGear.put("feet", player.getItemBySlot(EquipmentSlot.FEET).save(new CompoundTag()));
            }
            awakeningConfig.setActiveGear(player, activeGear);
            // 清除装备
            player.setItemSlot(EquipmentSlot.HEAD, ItemStack.EMPTY);
            player.setItemSlot(EquipmentSlot.CHEST, ItemStack.EMPTY);
            player.setItemSlot(EquipmentSlot.FEET, ItemStack.EMPTY);
            // 给予玩家60刻（3秒）的隐身效果
            player.addEffect(new MobEffectInstance(MobEffects.INVISIBILITY, 60, 0, false, false));
            // 添加球形推力效果
            if (player.level instanceof ServerLevel serverLevel) {
                SpecialEffectsUtils.createSphericalPushEffect(
                        serverLevel,
                        player.position(),
                        5.0,  // 半径5格
                        3,  // 推力强度3
                        player
                );
            }
        });


        // 7. 延迟装备完整装甲套装和保存数据
        DelayedTask.run(player.level, 260, () -> {
            awakeningConfig.equipFullArmorSet(player);
            // 设置状态
            fullRiderConfig.setCurrentState(player, HenshinState.ACTIVE_AWAKENING);

            // 保存数据
            dataManager.setHenshining(false);
            dataManager.saveToPlayer(player);
            dataManager.sync(player);
        });
    }

    /**
     * 生成变身特效实体
     */
    private void spawnSpecialEffects(Player player) {
        if (player.level instanceof ServerLevel serverLevel) {
            // 创建特效实体
            GeizmajestyspecialeffectsEntity effectEntity = new GeizmajestyspecialeffectsEntity(
                    KamenRiderZioAddonModEntities.GEIZMAJESTYSPECIALEFFECTS.get(),
                    serverLevel
            );
            // 设置位置为玩家位置
            double verticalOffset = 0.0; // 地面
            //effectEntity.setPos(player.getX(), verticalOffset, player.getZ());
            effectEntity.moveTo(player.getX(), verticalOffset, player.getZ(), player.getYRot(), 0);
            // 绑定玩家 - 使用驯服机制
            effectEntity.tame(player);

            // 同步身体旋转角度
            effectEntity.setYRot(player.getYRot());
            // 同步视觉旋转角度
            effectEntity.yBodyRot = player.yBodyRot;
            effectEntity.yBodyRotO = player.yBodyRotO;

            // 设置初始状态
            effectEntity.getPersistentData().putBoolean("henshin", true);

            // 添加实体到世界
            serverLevel.addFreshEntity(effectEntity);

            // 延迟重置状态并移除
            DelayedTask.run(player.level, 240, () -> {
                effectEntity.getPersistentData().remove("henshin");
                DelayedTask.run(player.level, 20, effectEntity::discard);
            });
        }
    }

    /**
     * 处理强化形态解除变身
     * @param player 玩家实例
     * @param fullRiderConfig 基础骑士配置
     * @param awakeningConfig 强化形态配置
     */
    @Override
    public void handleAwakeningDeactivation(Player player, FullRiderConfig fullRiderConfig, AwakeningConfig awakeningConfig) {
        HenshinState currentState = fullRiderConfig.getCurrentState(player);

        if (currentState == HenshinState.STANDBY_AWAKENING) {
            HenshinUtils.restoreStandbyGear(player);
        } else if (currentState == HenshinState.ACTIVE_AWAKENING) {
            HenshinUtils.restorePlayerGear(player);
        }

        //停止音效
        HenshinUtils.stopSound(player, fullRiderConfig.getSoundMap().get(SoundType.DRIVER));
        HenshinUtils.stopSound(player, fullRiderConfig.getSoundMap().get(SoundType.STANDBY));
        HenshinUtils.stopSound(player, fullRiderConfig.getSoundMap().get(SoundType.TRANSFORM));
        HenshinUtils.stopSound(player, awakeningConfig.getAwakeningSounds().get(SoundType.STANDBY));
        HenshinUtils.stopSound(player, awakeningConfig.getAwakeningSounds().get(SoundType.TRANSFORM));

        //立即清除玩家的隐身效果
        player.removeEffect(MobEffects.INVISIBILITY);

        // 清除已经存储的装备
        HenshinUtils.clearGearData(player);
        fullRiderConfig.setCurrentState(player, HenshinState.INACTIVE);

        // 保存数据
        PlayerDataManager.get(player).saveToPlayer(player);
        PlayerDataManager.get(player).sync(player);
    }
}
